/*
 * Created on 2008-2-11
 *
 */
package jacky.lanlan.song.extension.struts.util.bean;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 解析 {@link java.util.Date} 的PropertyEditor，使用 {@link DateFormat} 完成解析过程。
 * <p>
 * <i style="color:red;font-size:13px;">接收的字符串格式(Pattern)：yyyy-MM-dd</i>
 * </p>
 * 线程安全。
 */
public class DateEditor extends PropertyEditorSupport {

	private final DateFormat dateFormat=DateFormat.getDateInstance();

	private final Lock lock=new ReentrantReadWriteLock().readLock(); 
	
	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	public void setAsText(String text) throws IllegalArgumentException {
		try {
			lock.lock();
			setValue(this.dateFormat.parse(text));
		}
		catch (ParseException ex) {
			throw new IllegalArgumentException("Could not parse date: " + ex.getMessage());
		}
		finally {
			lock.unlock();
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	public String getAsText() {
		Date value = (Date) getValue();
		String strValue=null;
		try {
			lock.lock();
			strValue = this.dateFormat.format(value);
		}
		finally {
			lock.unlock();
		}
		return (value != null ? strValue : "");
	}

	public static final PropertyEditor INSTANCE=new DateEditor ();
	
}
